﻿package 
{
	import flash.filesystem.*;
	import flash.events.Event;
	import flash.xml.*;

	public class Logger
	{
		public static function saveFile(task_number, description, time, deleteLog=false):void
		{
			//var file:File=File.applicationStorageDirectory;
			var date:Date = new Date();
			var filename:String=task_number;
			var target:File = File.documentsDirectory.resolvePath(
				"TaskTimer/"+date.fullYear + '-' + (date.month+1) + '-' + (date.date)+'/'+filename+'.xml'
			);
			var targetParent:File=target.parent;
			targetParent.createDirectory();
			var fileStream:FileStream = new FileStream();
			fileStream.open(target, FileMode.WRITE);

			var log_content:XML = 
<tasks>
	<task>
		<task_number>{task_number}</task_number>
		<description>{description}</description>
		<time>{time}</time>
		<deleted>{deleteLog}</deleted>
	</task>
</tasks>;
			
			var newXMLStr:String = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" + log_content.toXMLString();
			
			fileStream.writeUTFBytes(newXMLStr);
			//fileStream.addEventListener(Event.CLOSE, fileClosed);
			fileStream.close();
		}
		
		public static function remove_old_log(filename)
		{
			var date:Date = new Date();
			var target:File = File.documentsDirectory.resolvePath(
				"TaskTimer/"+date.fullYear + '-' + (date.month+1) + '-' + (date.date+1)+'/'+filename
			);
			if(target.exists)
			{
				target.deleteFile();
			}
		}
		
		public static function loadLogs(date)
		{
			var date:Date = new Date();
			var target:File = File.documentsDirectory.resolvePath(
				"TaskTimer/"+date.fullYear + '-' + (date.month+1) + '-' + (date.date)+'/'
			);
			if(target.exists)
			{
				for each(var file:File in target.getDirectoryListing())
				{
					var fileStream:FileStream = new FileStream();
					fileStream.open(file, FileMode.READ);
					var log = XML(fileStream.readUTFBytes(fileStream.bytesAvailable));
					if(log.task.deleted=='false')
					{
						Main.new_timer(log.task.time, log.task.task_number, log.task.description);
					}
					fileStream.close();
				}
			}
		}

		private function fileClosed(event:Event):void
		{
			trace("closed event fired");
		}
		
	}
}